<?php
namespace app\index\controller;

class Index {
    public function index() {
    	$ctext = model('Text');
    	$texts_data = $ctext::where('if_top', 0)->where('type', 0)->order('create_time', 'desc')->paginate(12);
        $top_texts_data = $ctext::where('if_top', 1)->order('modify_time', 'desc')->select();
        $cuser = model('User');
        $heat_user = $cuser::order('heat', 'desc')->limit(15)->select();

        $user_avator_path = null;
        $user_introduction = null;
        $like_list = array();
        if (session('?user_id')) {
            $user_id = session('user_id');
            
            $user_data = $cuser::where('id', $user_id)->find();
            if ($user_data) {
                $user_avator_path = $user_data->avator_path;
                $user_introduction = $user_data->introduction;
            }
            $clike = model('Like');
            $likes_data = $clike::where('uid', $user_id)->where('if_like', 1)->select();
            if ($likes_data) {
                foreach($likes_data as $like_data) {
                    array_push($like_list, $like_data->tid);
                }
            }
        }
    	   	
        return view('/index/index', [
        	'texts' => $texts_data,
            'top_texts' => $top_texts_data,
            'like_list' => $like_list,
            'heat_user' => $heat_user
        ]);
    }

    public function calculateHeat() {
        $cuser = model('User');
        $ctext = model('Text');
        $creply = model('Reply');
        $clike = model('Like');
        $users = $cuser::all();

        foreach ($users as $user) {
            $texts = $ctext::where('uid', $user->id)->select();
            $reply_num = 0;
            $like_num = 0;
            foreach ($texts as $text) {
                $reply_num += $creply::where('tid', $text->id)->count();
                $like_num += $clike::where('tid', $text->id)->where('if_like', 1)->count();
            }
            $text_num = $ctext::where('uid', $user->id)->count();
            $heat = $text_num * 10 + $reply_num * 5 + $like_num * 2;
            dump($heat);
            dump($user->id);
            $cuser->isUpdate(true)->save(['id' => $user->id, 'heat' => $heat]);
        }

    }

    public function index1() {
        return "<h2>正在更新维护中…………</h2>";
    }
}
